import {useLocation} from "react-router-dom"
import {useMemo} from "react"
type methods={
    set:(value:any)=>void
    rm:()=>void
}
// 因为window对storage类型的限制，重新声明window
declare global {
    interface Window{
        [k:string]:any
    }
}
// key==>存储本地存储的key、 value===》存储本地存储的值、storageType===>本地存储的类型
type Istorage = (key: string, storageType?: string) => [string | null, methods]

const useStorage: Istorage = (key, storageType = 'localStorage') => {
    // 使用useMemo从本地取出结果
    let location=useLocation();
    let localVal=useMemo<string | null>(()=>{
        let valueRes:string | null;
        try{
            // 从本地获取
            valueRes=window[storageType].getItem(key)
            valueRes=valueRes ? JSON.parse(valueRes!) : null
            return valueRes
        }catch(e:any){
            console.log(e.toString)
            return null
        }
    },[location])

    // 存到本地+移除
    let methodObj:methods={
        // 设定缓存
        set:(value:any)=>{
            let valueJson;
            try{
                valueJson=JSON.stringify(value!)
                window[storageType].setItem(key,valueJson!)
            }catch(e:any){
                console.log(e.toString())
            }
        },
        // 移除
        rm:()=>{
            window[storageType].removeItem(key)
        }
    }


    return [localVal,methodObj]

}
export default useStorage
  